import { Injectable } from '@angular/core';

declare const monaco: any;

@Injectable({
  providedIn: 'root'
})
export class MonacoEditorService {
  private editorLoaded = false;
  private loadingPromise: Promise<void> | null = null;

  constructor() { }

  // 加载 Monaco Editor
  async loadMonacoEditor(): Promise<void> {
    if (this.editorLoaded) {
      return Promise.resolve();
    }

    if (this.loadingPromise) {
      return this.loadingPromise;
    }

    this.loadingPromise = new Promise((resolve, reject) => {
      // 设置 Monaco Editor 环境
      (window as any).MonacoEnvironment = {
        getWorkerUrl: function (moduleId: string, label: string) {
          if (label === 'json') {
            return '/assets/monaco/language/json/json.worker.js';
          }
          if (label === 'css' || label === 'scss' || label === 'less') {
            return '/assets/monaco/language/css/css.worker.js';
          }
          if (label === 'html' || label === 'handlebars' || label === 'razor') {
            return '/assets/monaco/language/html/html.worker.js';
          }
          if (label === 'typescript' || label === 'javascript') {
            return '/assets/monaco/language/typescript/ts.worker.js';
          }
          return '/assets/monaco/editor/editor.worker.js';
        }
      };

      // 动态加载 Monaco Editor
      if (typeof (window as any).monaco !== 'undefined') {
        this.editorLoaded = true;
        resolve();
        return;
      }

      // 加载Monaco Editor脚本
      const script = document.createElement('script');
      script.src = '/assets/monaco/loader.js';
      script.onload = () => {
        (window as any).require.config({ paths: { vs: '/assets/monaco' } });
        (window as any).require(['vs/editor/editor.main'], () => {
          this.editorLoaded = true;
          resolve();
        }, reject);
      };
      script.onerror = reject;
      document.head.appendChild(script);
    });

    return this.loadingPromise;
  }

  // 创建编辑器实例
  createEditor(container: HTMLElement, options: any): any {
    if (!this.editorLoaded || typeof (window as any).monaco === 'undefined') {
      throw new Error('Monaco Editor not loaded');
    }

    const monacoOptions = {
      value: options.value || '',
      language: options.language || 'typescript',
      theme: 'vs-light',
      automaticLayout: true,
      minimap: { enabled: false },
      scrollBeyondLastLine: false,
      wordWrap: 'on',
      renderLineHighlight: 'none',
      glyphMargin: true,
      lineNumbersMinChars: 4,
      readOnly: options.readOnly || false,
      ...options
    };

    return (window as any).monaco.editor.create(container, monacoOptions);
  }

  // 设置编辑器内容
  setEditorContent(editor: any, content: string, language?: string): void {
    if (!editor) return;

    const monaco = (window as any).monaco;
    if (monaco && language) {
      const model = monaco.editor.createModel(content, language);
      editor.setModel(model);
    } else if (editor.setValue) {
      editor.setValue(content);
    }
  }

  // 高亮显示特定行
  highlightLines(editor: any, startLine: number, endLine: number, className = 'highlighted-line'): string[] {
    if (!editor || typeof (window as any).monaco === 'undefined') {
      return [];
    }

    const monaco = (window as any).monaco;
    const range = new monaco.Range(startLine, 1, endLine, 1);
    
    return editor.deltaDecorations([], [{
      range: range,
      options: {
        isWholeLine: true,
        className: className,
        glyphMarginClassName: 'glyph-margin-highlight'
      }
    }]);
  }

  // 显示指定行范围
  revealLines(editor: any, startLine: number, endLine: number): void {
    if (editor && editor.revealLinesInCenter) {
      editor.revealLinesInCenter(startLine, endLine, 0);
    }
  }

  // 销毁编辑器
  destroyEditor(editor: any): void {
    if (editor && editor.dispose) {
      editor.dispose();
    }
  }

  // 检查Monaco是否已加载
  isLoaded(): boolean {
    return this.editorLoaded && typeof (window as any).monaco !== 'undefined';
  }
} 